package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.CustomException;
import com.demo.common.R;
import com.demo.dao.CategoryDao;
import com.demo.dao.DishDao;
import com.demo.dao.DishFlavorDao;
import com.demo.domain.*;
import com.demo.dto.DishDto;
import com.demo.service.CategoryService;
import com.demo.service.DishFlavorService;
import com.demo.service.DishService;
import com.demo.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.awt.datatransfer.FlavorEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishDao dishDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R<Page> page(int page, int pageSize, String name) {
        //添加分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //添加查询构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加模糊查询
        lqw.like(!StringUtils.isEmpty(name), Dish::getName, name);
        //添加排序规则
        lqw.orderByDesc(Dish::getUpdateTime);
        //执行查询
        this.page(pageInfo, lqw);

        //将pageInfo中的数据拷贝到dishdto中，因为dish表中没有菜品分类名
        //去除pageInfo中的records，因为数据类型不同，需要处理
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        //获取到pageInfo中records的数据
        List<Dish> records = pageInfo.getRecords();

        //通过Steam流的方式处理pageInfo中的records数据
        List<DishDto> list = records.stream().map((item) -> {
            //因为是new出来的dishdto所以需要拷贝item中的数据
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取到records中的菜品分类的id
            Long categoryId = item.getCategoryId();
            //通过菜品id获取到category对象
            Category category = categoryDao.selectById(categoryId);
            if (category != null) {
                //通过对象获取到分类名
                String categoryName = category.getName();
                //将分类名赋值到的dishdto中
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将disi中的Records重新赋值
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 代码优化
     * 多表条件分页查询
     *
     * @param dishDtoPage
     * @param dishDto
     */
    @Override
    public void pageByParams(Page<DishDto> dishDtoPage, DishDto dishDto) {
        dishDao.pageByParams(dishDtoPage, dishDto);
    }

    /**
     * 添加菜品信息
     *
     * @param dishDto
     * @return
     */
    @Override
    @Transactional
    public R<DishDto> dishsave(@RequestBody DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //获取菜品的id
        Long dishid = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishid);
            return item;
        }).collect(Collectors.toList());

        //将口味添加到菜品口味表中dishFlavor
        dishFlavorService.saveBatch(flavors);

        //获取到redis中所有菜品分类的key
        Set keys = redisTemplate.keys("dish_"+dishDto.getCategoryId()+"_1");
        //删除所有的key
        redisTemplate.delete(keys);

        return R.success(dishDto);
    }


    /**
     * 单删除和批量删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public R<String> deleteById(Long[] ids) {
        //查询当前菜品是否为起售状态
        LambdaUpdateWrapper<Dish> dishlqw = new LambdaUpdateWrapper<>();
        dishlqw.in(Dish::getId, Arrays.asList(ids));
        dishlqw.eq(Dish::getStatus, 1);
        int count = this.count(dishlqw);

        //查询菜品是否在某个套餐中
        LambdaQueryWrapper<SetmealDish> setmealDishlqw = new LambdaQueryWrapper<>();
        setmealDishlqw.in(SetmealDish::getDishId, Arrays.asList(ids));
        int count1 = setmealDishService.count(setmealDishlqw);
        log.info(String.valueOf(count1));
        if (count1 > 0) {
            throw new CustomException("套餐中包含该菜品，无法删除");
        }
        //当count大于0时代表删除的菜品中存在起售菜品
        //并抛出异常提示信息
        if (count > 0) {
            throw new CustomException("当前菜品正在售卖中，无法删除");
        } else {
            this.removeByIds(Arrays.asList(ids));
            //还需要删除口味关系表中的数据
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.in(DishFlavor::getDishId, Arrays.asList(ids));
            dishFlavorService.remove(lqw);
//        LambdaQueryWrapper<Dish> lqw  =new LambdaQueryWrapper<>();
            //  in   选中集合中的id
//        lqw.in(Dish::getId,Arrays.asList(ids));
//        this.remove(lqw);

            //获取到redis中所有的key
            Set keys = redisTemplate.keys("dish_*");
            //删除所有的key
            redisTemplate.delete(keys);

            return R.success("删除成功");
        }
    }


    /**
     * 修改菜品起售与停售状态
     *
     * @param status
     * @param ids
     * @return
     */
    @Override
    public R<String> updateStatus(@PathVariable int status, Long[] ids) {
        for (Long id : ids) {

            LambdaUpdateWrapper<Dish> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Dish::getId, id).set(Dish::getStatus, status);
            this.update(lambdaUpdateWrapper);
        }

        //获取到redis中所有的key
        Set keys = redisTemplate.keys("dish_*");
        //删除所有的key
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    /**
     * 根据id回显菜品基本信息和口味信息
     *
     * @param id
     * @return
     */
    @Override
    public R<DishDto> getDishWithFlavor(Long id) {
        //获取菜品的基本信息
        Dish dish = this.getById(id);
        //将基本信息复制给dishdto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        //获取菜品的口味信息
        LambdaQueryWrapper<DishFlavor> flavorlqw = new LambdaQueryWrapper<>();
        flavorlqw.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(flavorlqw);

        //将口味信息赋值给dishdto
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /**
     * 一对多查询  代码优化
     * 通过id回显数据
     *
     * @param id
     * @return
     */
    @Override
    public DishDto queryById(Long id) {
        return dishDao.queryById(id);
    }


    /**
     * 修改菜品信息以及口味
     *
     * @param dishDto
     * @return
     */
    @Override
    @Transactional
    public R<String> updateDishWithFlavor(@RequestBody DishDto dishDto) {
        //将基本信息保存
        this.updateById(dishDto);

        //删除DishFlavor表中的口味信息
        LambdaQueryWrapper<DishFlavor> flavorlqw = new LambdaQueryWrapper<>();
        flavorlqw.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(flavorlqw);

        //再将新的口味信息添加进去
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        //获取到redis中所有的key
        Set keys = redisTemplate.keys("dish_*");
        //删除所有的key
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    /**
     * 根据菜品类型id获取到对应的所有菜品
     *
     * @param dish
     * @return
     */
   /* @Override
    public R<List<Dish>> queryDishList(Dish dish) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //判断当前菜品是否为起售状态
        lqw.eq(Dish::getStatus, 1);
        //根据菜名查询数据
        lqw.eq(dish.getName() != null, Dish::getName, dish.getName());

        //获取到的数据封装到list中
        List<Dish> list = this.list(lqw);
        return R.success(list);
    }*/


    /**
     * 根据菜品类型id获取到对应的所有菜品
     *
     * @param dish
     * @return
     */
    @Override
    public R<List<DishDto>> queryDishList(Dish dish) {

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //判断当前菜品是否为起售状态
        lqw.eq(Dish::getStatus, 1);
        //根据菜名查询数据
        lqw.eq(dish.getName() != null, Dish::getName, dish.getName());

        //获取到的数据封装到list中
        List<Dish> list = this.list(lqw);

        //dish表中缺少口味信息
        List<DishDto> dishDtolist = list.stream().map((item) -> {
            //因为是new出来的dishdto所以需要拷贝item中的数据
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取到records中的菜品分类的id
            Long categoryId = item.getCategoryId();
            //通过菜品id获取到category对象
            Category category = categoryDao.selectById(categoryId);
            if (category != null) {
                //通过对象获取到分类名
                String categoryName = category.getName();
                //将分类名赋值到的dishdto中
                dishDto.setCategoryName(categoryName);
            }
            //获取到dish表中的id
            Long dishid = item.getId();
            //查询口味表中对应的口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishid);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            //将查询到的口味信息赋值到dishDto中
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtolist);
    }

    /**
     * 根据菜品类型id获取到对应的所有菜品
     * 代码优化
     * @param dish
     * @return
     */
    @Override
    public List<DishDto> DishList(Dish dish) {
        return this.dishDao.DishList(dish);
    }

}
